package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.domain.BaseEntity;
import com.xinghai.common.utils.DataUtil;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.uuid.IdUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.entity.*;
import com.xinghai.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物专区api接口
 *
 * @author xinghai
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/api/shop")
public class QdShopApiController extends BaseController
{
    @Autowired
    private IQdUserWalletService userWalletService;
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdUserPointsLogService userPointsLogService;
    @Autowired
    private IQdShopGoodService shopGoodService;
    @Autowired
    private IQdShopOrderService shopOrderService;


    /**
     * 查询商品列表
     */
    @GetMapping("/getGoodList")
    public AjaxResult getGoodList(Integer pageNum, Integer pageSize)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        QdShopGood qdShopGood = new QdShopGood();
        qdShopGood.setStoreId(user.getAscriptionStore());
        qdShopGood.setStatus("0");
        PageUtils.startPage(pageNum,pageSize);
        return success(getDataTable(shopGoodService.list(qdShopGood)));
    }

    /**
     * 查询订单列表
     */
    @GetMapping("/getOrderList")
    public AjaxResult getOrderList(Integer pageNum, Integer pageSize)
    {
        String userId = StpUtil.getLoginId("");
        QdShopOrder order = new QdShopOrder();
        order.setBuyerUserId(Long.valueOf(userId));
        order.setStatus("0");
        PageUtils.startPage(pageNum,pageSize);
        List<QdShopOrder> list = shopOrderService.list(order);
        return success(getDataTable(list));
    }


    /**
     * 查询店长收款信息
     */
    @GetMapping("/getPayInfo")
    public AjaxResult getPayInfo()
    {
        String userId = StpUtil.getLoginId("");
        QdUser qdUser = userService.getById(userId);
        QdUser user = userService.getById(qdUser.getStoreLeaderId());
        Map<String,Object> map = new HashMap<>();
        map.put("bankName",user.getBankName());//银行名称
        map.put("bankNo",user.getBankNo());//银行卡号
        map.put("bankInfo",user.getBankInfo());//开户行
        map.put("userName",user.getNickName());//店长名称
        map.put("userPhone",user.getUserPhone());//店长手机号
        return success(map);
    }

    /**
     * 下单购买
     */
    @PostMapping("/placeOrder")
    public AjaxResult placeOrder(@Validated @RequestBody QdShopGoodOrderDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        QdShopGood shopGood = shopGoodService.getById(dto.getGoodId());
        QdShopOrder shopOrder = new QdShopOrder();
        shopOrder.setBuyerUserId(Long.valueOf(userId));
        shopOrder.setStoreId(user.getAscriptionStore());
        shopOrder.setBuyerUserName(user.getNickName());
        shopOrder.setBuyerUserPhone(user.getUserPhone());
        shopOrder.setBuyerStatus("1");
        shopOrder.setOrderNo("GW"+IdUtil.getSnowflakeNextId());
        shopOrder.setGoodId(dto.getGoodId());
        shopOrder.setGoodName(shopGood.getGoodName());
        shopOrder.setGoodImg(shopGood.getGoodImg());
        shopOrder.setPrice(shopGood.getGoodPrice());
        shopOrder.setBuyNum(dto.getGoodNum());
        shopOrder.setAmount(shopGood.getGoodPrice().multiply(new BigDecimal(dto.getGoodNum())));
        shopOrder.setPoints(shopGood.getGoodPoint().multiply(new BigDecimal(dto.getGoodNum())));
        shopOrder.setDealTime(DateUtils.getNowDate());
        return success(shopOrderService.save(shopOrder));
    }
    /**
     * 查询商品列表(店铺)
     */
    @GetMapping("/store/getGoodList")
    public AjaxResult getStoreGoodList(Integer pageNum, Integer pageSize)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        QdShopGood qdShopGood = new QdShopGood();
        qdShopGood.setStoreId(user.getAscriptionStore());
        PageUtils.startPage(pageNum,pageSize);
        return success(getDataTable(shopGoodService.list(qdShopGood)));
    }

    /**
     * 查询发货信息
     */
    @GetMapping("/store/getAddress")
    public AjaxResult getAddress(String orderId)
    {
        QdShopOrder order = shopOrderService.getById(orderId);
        Long userId = order.getBuyerUserId();
        QdUser user = userService.getById(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("address",user.getAddress());
        map.put("province",user.getProvince());
        map.put("city",user.getCity());
        map.put("area",user.getArea());
        map.put("userName",user.getNickName());
        map.put("userPhone",user.getUserPhone());
        return success(map);
    }

    /**
     * 查询订单列表(店铺)
     */
    @GetMapping("/store/getOrderList")
    public AjaxResult getStoreOrderList(Integer pageNum, Integer pageSize,String search, String status,String date)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        QdShopOrder order = new QdShopOrder();
        order.setStoreId(user.getAscriptionStore());
        order.setStatus("0");
        order.setBuyerStatus(status);
        order.setSearchValue(search);
        if (StringUtils.isNotBlank(date)){
            order.setParams(DataUtil.getCreateTimeParams2(date));
        }
        PageUtils.startPage(pageNum,pageSize);
        List<QdShopOrder> list = shopOrderService.list(order);
        return success(getDataTable(list));
    }

    /**
     * 确认支付
     */
    @PostMapping("/store/confirmPayment")
    public AjaxResult confirmPayment(@Validated @RequestBody QdShopOrderDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        return success(shopOrderService.confirmPayment(dto));
    }

    /**
     * 取消订单
     */
    @PostMapping("/store/cancelOrder")
    public AjaxResult cancelOrder(@Validated @RequestBody QdShopOrderDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        return success(shopOrderService.cancelOrder(dto));
    }

    /**
     * 发货
     */
    @PostMapping("/store/sendOut")
    public AjaxResult sendOut(@Validated @RequestBody QdShopOrderDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        //发货，修改订单状态
        Long orderId = dto.getOrderId();
        QdShopOrder order = shopOrderService.getById(orderId);
        if (!"2".equals(order.getBuyerStatus())){
            return error("订单状态错误，无法发货");
        }
        order.setBuyerStatus("3");
        return success(shopOrderService.updateById(order));
    }

    /**
     * 删除商品
     */
    @PostMapping("/store/delGood")
    public AjaxResult delGood(@RequestBody QdShopGoodStatusDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        if (dto.getGoodId()==null){
            return error("商品id不能为空");
        }
        QdShopGood shopGood = new QdShopGood();
        shopGood.setId(dto.getGoodId());
        shopGood.setDelFlag(GenConstants.DELETE_FLAG_YES);
        return success(shopGoodService.updateById(shopGood));
    }
    /**
     * 上传商品信息
     */
    @PostMapping("/store/addGood")
    public AjaxResult addGood(@Validated @RequestBody QdShopGoodDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        QdShopGood shopGood = new QdShopGood();
        BeanUtils.copyProperties(dto,shopGood);
        shopGood.setStoreId(user.getAscriptionStore());
        shopGood.setStoreLeader(user.getStoreLeader());
        shopGood.setStoreLeaderImg(user.getStoreLeaderImg());
        shopGood.setStoreLeaderPhone(user.getStoreLeaderPhone());
        shopGood.setStoreName(user.getStoreName());
        shopGood.setStoreLeaderId(user.getId());
        shopGood.setStatus("1");
        return success(shopGoodService.save(shopGood));
    }

    /**
     * 上传商品信息
     */
    @PostMapping("/store/updateGood")
    public AjaxResult updateGood(@Validated @RequestBody QdShopGoodDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        if (dto.getGoodId() == null){
            return error("商品id不能为空");
        }
        QdShopGood shopGood = new QdShopGood();
        shopGood.setId(dto.getGoodId());
        BeanUtils.copyProperties(dto,shopGood);
        return success(shopGoodService.updateById(shopGood));
    }

    /**
     * 修改商品状态
     */
    @PostMapping("/store/updateStatus")
    public AjaxResult updateStatus(@Validated @RequestBody QdShopGoodStatusDTO dto)
    {
        String userId = StpUtil.getLoginId("");
        QdUser user = userService.getById(userId);
        if (user.getAscriptionStore() == null||!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        QdShopGood shopGood = new QdShopGood();
        shopGood.setId(dto.getGoodId());
        shopGood.setStatus(dto.getStatus());
        return success(shopGoodService.updateById(shopGood));
    }

}
